<?php

@session_start();

require 'conf.php';

function redirect_successful()
{
    echo "<html><head><script>window.location = '/';</script></head></html>";
}
function redirect_with_message($msg)
{
    echo "<html><head><meta charset='utf-8'><script>alert('$msg'); window.location = '/';</script></head></html>";
}

function suicide($sessiontoken){
    global $MW_host;
    $fields = array('USR_SUICIDE' => '',
                    'SESSION' => $sessiontoken);

    $fields = http_build_query($fields);

    $h = curl_init($MW_host);
    curl_setopt($h, CURLOPT_POST, 1);
    curl_setopt($h, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));

   $res = curl_exec($h);
    
    if(!mb_check_encoding($res, 'UTF-8'))
        $res = utf8_encode($res);
    $data = json_decode($res);
    return $data;
}

$res;
if (isset($_SESSION['sessiontoken'])) {
    $res = suicide($_SESSION['sessiontoken']);
}

unset($_SESSION['username']);
unset($_SESSION['sessiontoken']);

if($res === null){
    redirect_with_message("Ett fel uppstod i komunikationen med mellan-servern");
}else if (isset($res->error)) {
    redirect_with_message($res->error);
}else{
    redirect_successful();
}

?>
